package org.robot.scm.platform.monitor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.time.LocalTime;
import java.util.List;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.infra.RedisCacheHelper;
import org.robot.scm.platform.AbstractMonitor;
import org.robot.scm.pojos.BaseNotify;
import org.robot.scm.pojos.config.BaseConfig;
import org.robot.scm.pojos.enums.PlatformEnum;
import org.robot.scm.pojos.platform.IBoxBaseNotify;
import org.robot.scm.pojos.proxy.ProxyInfo;
import org.robot.scm.utils.DateTool;
import org.robot.scm.utils.RequestHelper;
import org.robot.scm.utils.StreamUtils;

/**
 * IBox监控 - Bark
 */
@Slf4j
public class IBoxNoticeMonitor extends AbstractMonitor {

    @Override
    public PlatformEnum getPlatform() {
        return PlatformEnum.IBOX;
    }

    private static boolean telnet(String ipPort, int timeout) {
        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(ipPort.split(":")[0], Integer.parseInt(ipPort.split(":")[1])), timeout);
            return socket.isConnected();
        } catch (IOException e) {
            return false;
        }
    }

    /**
     * 10 - 22点之间？
     */
    public static boolean isDaytime() {
        LocalTime now = LocalTime.now();
        return now.isAfter(LocalTime.of(10, 0)) && now.isBefore(LocalTime.of(22, 0));
    }

    @SneakyThrows
    @Override
    public BaseNotify doMonitor(BaseConfig config) {
        try {
            String proxyIp = RedisCacheHelper.get("ibox.proxy");
            if ((StringUtils.isBlank(proxyIp) || !telnet(proxyIp.trim(), 2000)) && isDaytime()) {
                proxyIp = RequestHelper.get("http://api1.ydaili.cn/tools/BMeasureApi.ashx?action=BEAPI&secret=D7A07F043F0BF8594A82F05CF5348FF7E75C546D200875E3&number=1&orderId=SH20250220165500852&format=txt&split=3").trim();
                log.info("new ibox proxy ip: {}", proxyIp);
                RedisCacheHelper.put("ibox.proxy", proxyIp, 180);
            }
            config.getCurrentPlatform().setProxyInfo(new ProxyInfo(proxyIp));
            List<IBoxBaseNotify> noticeBeans = Lists.newArrayList();
            String result = RequestHelper.get(String.format(config.getCurrentPlatform().getNoticeSrc(), System.currentTimeMillis()), config.getCurrentPlatform().getProxyInfo());
            JSONArray array = JSON.parseObject(result).getJSONObject("data").getJSONArray("list");
            noticeBeans.addAll(StreamUtils.filter(array.toJavaList(IBoxBaseNotify.class), e -> filter(DateTool.parse(e.getCreatedAt()).getTime())));
            noticeBeans.sort((o1, o2) -> DateTool.parse(o2.getCreatedAt()).compareTo(DateTool.parse(o1.getCreatedAt())));
            return CollectionUtils.isNotEmpty(noticeBeans) ? noticeBeans.get(0) : null;
        } catch (Exception e) {
            log.info("ibox error: {}", e.getMessage());
            return null;
        }
    }

}
